package com.kumarn.android.catdroid.full;

import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.media.MediaPlayer;
import android.os.IBinder;

public class CatDroidService extends Service {

	public void onStart() {
	}

	@Override
	public void onCreate() {

		IntentFilter filter = new IntentFilter();
		filter.addAction(Intent.ACTION_SCREEN_ON);			//スクリーンON
		filter.addAction(Intent.ACTION_SCREEN_OFF);			//スクリーンOFF
		filter.addAction(Intent.ACTION_BATTERY_CHANGED);	//バッテリー監視
		filter.addAction(Intent.ACTION_DATE_CHANGED);		//日付変更
		registerReceiver(RECEIVER,filter);

	}

	@Override
	public IBinder onBind(Intent arg0) {
		return null;
	}

	public BroadcastReceiver RECEIVER = new BroadcastReceiver() {
		@Override
		public void onReceive(Context context, Intent intent) {
			//設定ファイル読み込み
			SharedPreferences pref = getSharedPreferences("CatDroidPref",MODE_WORLD_READABLE|MODE_WORLD_WRITEABLE);

			boolean RingTong = false;			//効果音再生フラグ
			String ACTION = intent.getAction();	//インテントアクション取得

			//スクリーンON時
			if(ACTION.equals(Intent.ACTION_SCREEN_ON) && pref.getBoolean("ACTION_SCREEN_ON", false)){
				RingTong = true;

			//スクリーンOFF時
			}else if(ACTION.equals(Intent.ACTION_SCREEN_OFF) && pref.getBoolean("ACTION_SCREEN_OFF", false)){
				RingTong = true;

			//日付変更時
			}else if(ACTION.equals(Intent.ACTION_DATE_CHANGED) && pref.getBoolean("ACTION_DATE_CHANGED", false)){
				RingTong = true;

			//バッテリー監視
			}else if(ACTION.equals(Intent.ACTION_BATTERY_CHANGED)){
				//int scale = intent.getIntExtra("scale", 0);
				int level = intent.getIntExtra("level", 0);

				Editor e = pref.edit();
				//初回100％時
				if(level == 100 && pref.getBoolean("ACTION_BATTERY_OKAY", false) && !pref.getBoolean("ACTION_BATTERY_OKAY_SINGLE", false)){
					RingTong = true;
					e.putBoolean("ACTION_BATTERY_OKAY_SINGLE", true);
					e.commit();
				//初回10%時
				}else if(level == 10 && pref.getBoolean("ACTION_BATTERY_LOW", false) && !pref.getBoolean("ACTION_BATTERY_LOW_SINGLE", false)){
					RingTong = true;
					e.putBoolean("ACTION_BATTERY_LOW_SINGLE", true);
					e.commit();
				}

				//二回目以降100％時
				if(level != 100){
					e.putBoolean("ACTION_BATTERY_OKAY_SINGLE", false);
					e.commit();
				}

				//二回目以降10％時
				if(level != 10){
					e.putBoolean("ACTION_BATTERY_LOW_SINGLE", false);
					e.commit();
				}
			}

			//効果音再生
			if(RingTong){
				MediaPlayer mediaPlayer = MediaPlayer.create(context,R.raw.cat);
				mediaPlayer.start();
			}
		}
	};

}